package site.wetsion.galio.auth.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sit.wetsion.galio.common.constant.AuthSecurityConstant;
import site.wetsion.galio.data.entity.RoleDO;
import site.wetsion.galio.data.entity.UserDO;
import site.wetsion.galio.data.entity.UserRoleDO;
import site.wetsion.galio.data.service.RoleService;
import site.wetsion.galio.data.service.UserRoleService;
import site.wetsion.galio.data.service.UserService;
import java.util.*;

/**
 * @author weixin
 * @version 1.0
 * @CLassName RmsUserDetailsService
 * @date 2019/3/6 2:41 PM
 */
@Service
public class RmsUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("请求的用户名不能为空");
        }
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.or();
        queryWrapper.eq("email", username);
        UserDO userDO = userService.getOne(queryWrapper);
        if (Objects.isNull(userDO)) {
            throw new UsernameNotFoundException("用户名或邮箱不存在");
        }
        List<UserRoleDO> userRoleDOS = userRoleService.list(
                new QueryWrapper<UserRoleDO>().eq("user_id", userDO.getId()));
        Set<String> authSet = new HashSet<>();
        for (UserRoleDO userRoleDO : userRoleDOS) {
            RoleDO role = roleService.getById(userRoleDO.getRoleId());
            authSet.add(AuthSecurityConstant.ROLE + role.getName());
        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));
        return new User(userDO.getUsername(), userDO.getPassword(), authorities);
    }
}
